//index.js
const app = getApp(); //获取应用实例
let request = require("../../utils/request.js"); //封装的request请求
let config = require("../../config/config.js");
let countTime = null;
let currOrderFlag = false;
let QQMapWx = require("../../utils/qqmap-wx-jssdk.js");
let qqmapsdk = new QQMapWx({ key: config.map_key });
let timeStamp = require("../../utils/time"); //计算停车时长时间

import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
import websocket from "../../utils/websocket";

const { myRequest } = require("../../utils/http.js");

Page({
  data: {
    userInfo: wx.getStorageSync("userInfo"),
    token: wx.getStorageSync("token"),
    stopingCarList: [],
    bottomShow: false,
    reorientation: 0,
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: app.globalData.screenHeight,
    show: false,
    longitude: 114.52,
    latitude: 38.02,
    scale: 12,
    markers: [],
    markerIds: [],
    hasmarkers: false,
    remainTime: 0,
    cardNumList: [],
    user: {},
    totalMyTicket: 0,
    haveCard: false,
    carNumber: "",
    parkList: [],
    searcheRecord: [],
    hasPhone: false,
    showMarkerModal: false,
    stopParkDialog: false,
    // stopMyCar: {},
    markerPark: {},
    searching: [],
    searchPark: [],
    showTabBar: true,
    unfoldRule: false,
    isSystemLocation: true, // 手机系统授权微信定位权限
    isLocalLocation: true, // 微信授权小程序定位权限
    searchResult: [],
    noSearchData: false,
    searchAddress: "",
    websocketUrl: app.globalData.websocketUrl + "customer/",
    customerLeftTime: {},
    showGoOutPark: false,
    showStop: false,
    // mapStyle: config.map_style,
    // stopCarDialog: false,
    stopCarOutDialog: false,
    stop_car_tips: "",
    parkImgCurr: 0,
    couponTipList: [],
    couponTipsDialog: false,
    touchStartX: 0,
    touchEndX: 0,
    parkInfoImageL: 0,
    customCalloutMarkerIds: [],
    customCalloutData: [],
    applyCar: [],
    applyCarIds: [],
    applyCarData: [],
    payBehalfDialog: false,
    city: null,
    selectedStopingCar: null, //  选中的场内车
    mapKey: config.map_key,
    searchList: [],
    parkingShow: false, //获取平台停车劵
    parkingList: [],
    authorizationPhone: false, //授权手机号
    orderState: false, //上一次的订单信息
    orderInfo: {}, //上次订单信息
    showParkTime: true, //未支付订单时间为空
    userinfo: "",
    swiperCurrent: "",
    page: [0, 1, 2],
    code: "",
    openNoninductive: true,
  },
  onLoad: function () {
    let that = this;
    console.log("index-on-load");
    console.log("userInfo信息：", this.data.userInfo);
    this.setData({ userInfo: wx.getStorageSync("userInfo") });
    wx.login({
      //先登录提前保存code
      success: (res) => {
        that.setData({
          code: res.code,
        });
      },
    });
    //  更新小程序
    this.miniProgranUpdate();
  },
  code(code) {
    request
      .http("/customer/info/get-customer-by-weixin-code", "GET", { code: code })
      .then((res) => {
        if (res.data.code == 200) {
          let data = res.data;
          console.log("code接口返回", data);
          if (data.data != null) {
            let userInfo = {
              avatarUrl: data.data.avatar,
              nickName: data.data.nickname,
            };
            wx.setStorageSync("token", data.data.token);
            wx.setStorageSync("userInfo", userInfo);
            wx.setStorageSync("customerId", data.data.id);
            console.log("token为", data.data.token);
            this.setData({
              token: data.data.token,
              userInfo: userInfo,
            });

            this.parkingList(); //  获取停车劵信息
            this.getCustomerLeftTime(); //  车主剩余服务
            this.openSocket(); //  打开socket
            this.getCouponTips(); //  卡券
            //订单信息
            this.orderInfo();
            if (!data.data.mobilePhone) {
              //判断有没有授权手机号   如果没有提示授权手机号
              this.setData({
                authorizationPhone: true,
              });
            } else {
              wx.setStorageSync("phoneNumber", data.data.mobilePhone);
            }
          }
          // 获取用户当前位置
          this.getLocation();
        }
      })
      .catch((err) => {
        console.error(err);
      });
  },

  onShow(res) {
    console.log("index-on-show");
    console.log("地理位置的系统开关：", wx.getSystemInfoSync().locationEnabled);
    console.log(
      "允许微信使用定位的开关：",
      wx.getSystemInfoSync().locationAuthorized
    );

    //  手机系统授权微信定位权限
    if (wx.getSystemInfoSync().locationAuthorized == false) {
      this.setData({ isSystemLocation: false });
      wx.setStorageSync("isSystemLocation", false);
      return;
    }
    //每次进来获取token
    wx.login({
      success: (res) => {
        this.code(res.code);
      },
    });
  },
  //关闭订单信息
  orderBind() {
    this.setData({
      orderState: false,
    });
  },
  //订单信息
  orderInfo() {
    let that = this;
    request
      .http("/order/info-trade-record/get-arrears-order", "GET", {})
      .then((res) => {
        let data = res.data.data;
        if (res.data.code == 200) {
          if (data.length != 0) {
            let orderInfo = data[0];
            console.log(orderInfo);
            let totalTime = timeStamp.timeStamp(orderInfo.parkDuration); // 停车时长，改为天时分
            if(data.length != 0) {
              // 查询车牌是否开通微信支付分服务
              let plateNumber = data[0].carNumber;
              console.log('查询车牌是否开通微信支付分服务');
              that.getParkingServices(plateNumber)
            }
            this.setData({
              orderInfo: data[0],
              totalTime,
              orderState: true,
            });
            console.log("订单信息", this.data.orderInfo);
          }
        }
      })
      .catch((err) => {
        console.error(err);
      });
  },
  /**
   * 支付
   */
  payment() {
    let _this = this;
    let orderData = this.data.orderInfo;
    //  支付垫付停车费
    let params = {
      totalAmount: orderData.paidAmount, //实付金额
      tradeRecordId: orderData.id, // 订单id
    };
    request
      .http("/order/info-trade-record/pay-behalf", "POST", params, 0)
      .then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          let orderCode = res.data.data.orderCode;
          //支付
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
            nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
            package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
            signType: "MD5", // 签名算法，非必填，（预先约定或者后台传回）
            paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
            success: function (res) {
              // 成功后的回调函数
              wx.showToast({ title: "支付成功" });
              setTimeout(function () {
                _this.setData({ orderState: false });
              }, 2000);
            },
            fail(res) {
              console.log(res);
            },
          });
        } else {
          // wx.showToast({ title: res.data.desc })
        }
      });
  },

  onReady() {
    //  创建地图
    this.MapContext = wx.createMapContext("myMap");
  },
  onUnload() {},
  onHide() {},
  /**
   * 获取停车场
   * @param {Number} longitude 经度
   * @param {Number} latitude 纬度
   */
  getParks(longitude, latitude) {
    request
      .http("/park/info/getParkList", "GET")
      .then((res) => {
        if (res.data.code == 200) {
          let parkList = res.data.data;
          let markers = [];

          //  停车场位置marker
          for (let i = 0; i < parkList.length; i++) {
            let pointWidth = 27;
            let pointHeight = 32;
            // if(parkList[i].hasParkTicket == 1 || parkList[i].reserveRuleStatus == 1) {
            //   pointWidth = 43
            //   pointHeight = 32
            // }
            let marker = this.getMarker(
              i + 1,
              parkList[i].longitude,
              parkList[i].latitude,
              this.getMarkerIcon(parkList[i]),
              pointWidth,
              pointHeight
            );
            markers.push(marker);
          }
          //  车主位置marker
          let myMarker = this.getMarker(
            0,
            longitude,
            latitude,
            "https://mis.lmtc.zmzncs.com/file/WeChat/location.png",
            26,
            34
          );
          markers.unshift(myMarker); //  数组头部插入
          this.setData({ parkList: parkList, markers: markers });

          //  移动到我的位置
          // if (longitude !== 0 && latitude !== 0) {
          //   this.MapContext.moveToLocation({ longitude, latitude })
          // }
        }
        //  显示在场车辆、预约成功marker
        if (wx.getStorageSync("token")) {
          this.getStopingCar(); //  在场车辆
          this.getReserve(); //  预约
        }
        //  车主位置实时监听
        this.locationChange();
      })
      .catch((err) => {
        console.error(err);
      });
  },
  /**
   * 获取用户时长卡/月卡
   */
  getCustomerLeftTime() {
    request.http("/customer/card/getCustomerLeftTime", "GET").then((res) => {
      console.log("卡券信息：", res);
      if (res.data.code == 200) {
        this.setData({ customerLeftTime: res.data.data });
      }
    });
  },
  /**
   * 获取用户停车信息
   */
  getStopingCar(isLoading) {
    var isLoading = isLoading == false ? isLoading : true;
    request
      .http("/order/orderInfo/getCustomerCarParkList", "GET", {}, isLoading)
      .then((res) => {
        console.log("在场车辆信息：", res);
        var data = res.data;
        if (data.code == 200) {
          let markers = this.data.markers;
          //是为了出场时  把地图的自定义气泡删除掉，不然还是会显示进场的气泡
          if (data.data.length != 0) {
            // markers.forEach((element, index) => {
            //     delete markers[index].customCallout;
            // });
          }

          let customCalloutMarkerIds = [];
          let customCalloutData = [];
          let stopingCarList = data.data;

          for (let i = 0; i < stopingCarList.length; i++) {
            stopingCarList[i].checked = false;
            this.setData({ showGoOutPark: true });
            markers.forEach((element, index) => {
              if (
                stopingCarList[i].latitude == element.latitude &&
                stopingCarList[i].longitude == element.longitude
              ) {
                markers[index]["customCallout"] = {
                  display: "ALWAYS",
                  anchorX: 0,
                  anchorY: 0,
                };
                customCalloutMarkerIds.push(element.id);
                customCalloutData.push(stopingCarList[i].carNumber);
              }
            });
          }
          this.setData({
            stopingCarList: stopingCarList,
            markers: markers,
            customCalloutMarkerIds: customCalloutMarkerIds,
            customCalloutData: customCalloutData,
          });
          console.log(this.data.customCalloutData);
          console.log(this.data.customCalloutMarkerIds);
        }
      });
  },
  /**
   * 预约坐标点位
   */
  getReserve() {
    request
      .http("/order-reserve/park-reserve-record/reserved-curr", "GET")
      .then((res) => {
        let data = res.data;
        if (data.code == 200) {
          let markers = this.data.markers;
          let applyCar = data.data;
          let applyCarIds = [];
          let applyCarData = [];
          for (var i = 0; i < applyCar.length; i++) {
            //  如果预约已经入场，则不显示预约marker
            if (applyCar[i].inParkOrderId) {
              continue;
            }
            markers.forEach((element, index) => {
              if (
                applyCar[i].latitude == element.latitude &&
                applyCar[i].longitude == element.longitude
              ) {
                markers[index]["customCallout"] = {
                  display: "ALWAYS",
                  anchorX: 0,
                  anchorY: 0,
                };
                applyCarIds.push(element.id);
                applyCarData.push(applyCar[i].parkingTime);
              }
            });
          }
          this.setData({
            applyCar: applyCar,
            markers: markers,
            applyCarIds: applyCarIds,
            applyCarData: applyCarData,
          });
        }
      });
  },
  /**
   * 关闭底部弹窗
   */
  bottomPopClose() {
    this.setData({
      bottomShow: false,
      noSearchData: false,
      searchAddress: "",
      searching: [],
    });
  },
  /**
   * 打开底部弹窗
   */
  showBottomPop() {
    let searcheRecord = wx.getStorageSync("searcheRecord");
    if (searcheRecord != null) {
      this.setData({
        searcheRecord: searcheRecord,
      });
    }
    this.setData({
      bottomShow: true,
    });
  },

  /**
   * 跳转到会员中心
   */
  toVip(e) {
    if (this.data.token) {
      this.setData({ stopCarOutDialog: false });
      wx.navigateTo({
        url:
          "/pages/pay/monthly/monthly?parkData=" +
          JSON.stringify(this.data.markerPark),
      });
    } else {
      //  获取用户信息
      this.getUserProfile({
        currentTarget: {
          dataset: {
            url:
              "/pages/pay/monthly/monthly?parkData=" +
              JSON.stringify(this.data.markerPark),
          },
        },
      });
    }
  },
  /**
   * 预约功能
   */
  reservePark() {
    let markerPark = this.data.markerPark;
    if (markerPark.reserveParkSpace == 0) {
      wx.showToast({
        title: "对不起，当前停车场暂无预约功能，请尝试预约其他停车场",
        icon: "none",
      });
      return;
    }
    request
      .http("/promotion/reserve-fee-scale/getMonthRulePaytypeByParkId", "GET", {
        parkId: markerPark.id,
      })
      .then((res) => {
        wx.navigateTo({
          url:
            "/pages/subscribe/subscribe?parkId=" +
            markerPark.id +
            "&parkName=" +
            markerPark.parkName +
            "&reserveParkSpace=" +
            markerPark.reserveParkSpace,
        });
      })
      .catch((err) => {
        wx.showToast({
          title: "对不起，当前停车场暂无预约功能，请尝试预约其他停车场",
          icon: "none",
        });
      });
  },
  //搜索点击下拉的数据     地图滑动
  searchMobile(e) {
    let item = e.detail;
    this.MapContext.moveToLocation({
      longitude: Number(item.longitude),
      latitude: Number(item.latitude),
    });
  },
  /**
   * 从搜索结果点击打开的  停车场详情
   */
  parkingInfo(e) {
    let item = e.detail;
    let markers = this.data.markers;
    let arr = [];
    markers.map((res, i) => {
      if (res.latitude == item.latitude && res.longitude == item.longitude) {
        markers[i]["customCallout"] = {
          display: "ALWAYS",
          anchorX: 0,
          anchorY: -2,
        };
        arr.push(res.id);
      }
    });
    this.setData({
      markerPark: item,
      showMarkerModal: true,
      bottomShow: false,
      searchList: arr,
      markers: markers,
    });
    this.MapContext.moveToLocation({
      longitude: Number(item.longitude),
      latitude: Number(item.latitude),
    });
  },
  /**
   * 点击地图上的标记
   */
  checkMarkerPark(e) {
    if (this.data.showMarkerModal) {
      return;
    }
    console.log(e);
    console.log(this.data.showMarkerModal);

    let id = e.detail.markerId;
    let that = this;
    if (id == 0) {
      Toast("这是您当前位置");
      this.setData({ showMarkerModal: false });
      return;
    }
    //  场内车marker
    if (/^stop/.test(id)) {
      if (currOrderFlag) {
        return;
      }
      currOrderFlag = true;
      id = id.substring(4);
      // this.getCurrOrder(id)
      //  停车场marker
    } else {
      let index = id - 1;
      let parkList = this.data.parkList;
      this.MapContext.moveToLocation({
        longitude: Number(parkList[index].longitude),
        latitude: Number(parkList[index].latitude),
      });
      this.calculateDistance(
        { longitude: that.data.longitude, latitude: that.data.latitude },
        [
          {
            longitude: parkList[index].longitude,
            latitude: parkList[index].latitude,
          },
        ],
        (res) => {
          let distances = (res.result.elements[0].distance / 1000).toFixed(2);
          request
            .http("/park/info/getParkInfoById", "GET", {
              parkId: parkList[index].id,
            })
            .then((parkRes) => {
              let data = parkRes.data;
              if (data.code == 200) {
                let parkInfo = data.data;
                parkInfo["distances"] = distances;
                parkInfo["id"] = parkList[index].id;
                this.setData({ markerPark: parkInfo, showMarkerModal: true });
              }
            });
        }
      );
    }
  },
  // 地图上的自定义气泡
  checkStopPark(e) {
    console.log("地图上的自定义气泡：", e);
    console.log(this.data.applyCarIds);
    console.log(this.data.stopingCarList);
    //预约信息   如果预约信息不等于空  并且 车辆信息等于空  表示展示的是 预约成功气泡  就走跳转预约列表
    if (
      this.data.applyCarIds.length != 0 &&
      this.data.stopingCarList.length == 0
    ) {
      wx.navigateTo({ url: "/pages/applayRecord/applayRecord?state=2" });
      return false;
    }
    let stopingCarList = this.data.stopingCarList;
    let marker = this.data.markers[e.detail.markerId];
    let selectedStopingCar = null;
    for (var i = 0; i < stopingCarList.length; i++) {
      if (
        marker.latitude == stopingCarList[i].latitude &&
        marker.longitude == stopingCarList[i].longitude
      ) {
        selectedStopingCar = stopingCarList[i];
      }
    }

    selectedStopingCar.checked = true;
    console.log("停车信息", stopingCarList);
    this.setData({
      selectedStopingCar: selectedStopingCar,
      stopingCarList: stopingCarList,
    });
    for (let res of stopingCarList) {
      console.log(res.parkSource);
      // 判断 parkSource ( 1、泊链2、咪网 3、道尔 4、腾达 ) 1或4显示停车信息弹窗， 判断是为了北国和火车站停车时间为空
      if (res.parkSource != null) {
        if (res.parkSource == 1 || res.parkSource == 4) {
          this.setData({
            // 去掉弹窗信息
            stopCarOutDialog: true,
          });
        }
      }
    }

    // this.getCurrOrder(index, true)
  },
  /**
   * 关闭停车信息弹窗
   */
  // hiddenStopParkDialog() {
  //   this.setData({ stopParkDialog: false })
  // },
  /**
   * 定位到当前位置
   */
  toLocationBtn() {
    this.MapContext.moveToLocation({
      longitude: Number(this.data.longitude),
      latitude: Number(this.data.latitude),
    });
  },
  /**
   * 右上角分享功能
   */
  onShareAppMessage: function (res) {
    return {
      title: "",
      path: "/pages/index/index",
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      },
    };
  },
  /**
   * 关闭弹窗
   */
  closeMarkerModal() {
    let that = this;
    this.setData({
      showMarkerModal: false,
      unfoldRule: false,
    });
    setTimeout(function () {
      that.setData({
        parkImgCurr: 0,
        parkInfoImageL: 0,
        markerPark: {},
      });
    }, 300);
  },
  /**
   * 从历史记录导航
   */
  historyToMap(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let searcheRecord = that.data.searcheRecord[index];
    let lat = searcheRecord.latitude;
    let lng = searcheRecord.longitude;
    let name = searcheRecord.place;
    let address = searcheRecord.address;
    let scale = 14;
    this.openLocation(lat, lng, name, address, scale);
  },
  /**
   * 从车场详情导航
   */
  toMapNavigation() {
    let that = this;
    that.closeMarkerModal();
    let markerPark = that.data.markerPark;
    let lat = markerPark.latitude;
    let lng = markerPark.longitude;
    let name = markerPark.parkName;
    let address = markerPark.parkAddress;
    let scale = 14;
    this.openLocation(lat, lng, name, address, scale);
  },
  /**
   * 搜索结果导航
   */
  searchingToMap(e) {
    let index = e.currentTarget.dataset.index;
    let searchingData = this.data.searching[index];
    let lat = searchingData.location.lat;
    let lng = searchingData.location.lng;
    let name = searchingData.title;
    let address = searchingData.address;
    let scale = 14;
    this.openLocation(lat, lng, name, address, scale);
  },
  /**
   * 搜索结果导航
   */
  searchParkToMap(e) {
    let index = e.currentTarget.dataset.index;
    let searchingData = this.data.searchResult[index];
    let lat = searchingData.latitude;
    let lng = searchingData.longitude;
    let name = searchingData.parkName;
    let address = searchingData.parkAddress;
    let scale = 14;
    this.openLocation(lat, lng, name, address, scale);
  },
  /**
   * 打开导航
   * @param {Number} lat 纬度
   * @param {Number} lng 经度
   * @param {String} name 地名
   * @param {String} address 地址
   * @param {Number} scale 缩放等级
   */
  openLocation(lat, lng, name, address, scale) {
    let latitude = Number(lat);
    let longitude = Number(lng);
    wx.openLocation({
      latitude,
      longitude,
      name: name,
      address: address,
      scale: scale,
    });
  },
  /**
   * 操作底部导航显示与隐藏
   */
  setTabBar() {
    this.setData({
      showTabBar: !this.data.showTabBar,
      showMarkerModal: false,
      unfoldRule: false,
    });
  },
  /**
   * 底部tab栏跳转
   * @param {*} e
   */
  toPage(e) {
    let token = wx.getStorageSync("token");
    if (token == null || token == "" || token == undefined) {
      if (e.currentTarget.dataset.path == "/pages/center/center") {
        wx.showToast({ title: "请先授权", icon: "none" });
        return;
      }
    }
    if (e.currentTarget.dataset.path == "/pages/index/index") {
      return;
    }
    wx.redirectTo({
      url: e.currentTarget.dataset.path,
    });
  },
  /**
   * 跳转到我的权益页面
   */
  toMyRights() {
    if (this.data.token) {
      wx.navigateTo({ url: "/pages/my-rights/myRights" });
    } else {
      //  获取用户信息
      this.getUserProfile({
        currentTarget: { dataset: { url: "/pages/my-rights/myRights" } },
      });
    }
  },
  /**
   * 跳转到我的页面
   */
  toMineTab() {
    if (this.data.token) {
      wx.redirectTo({ url: "/pages/center/center" });
    } else {
      //  获取用户信息
      this.getUserProfile({
        currentTarget: { dataset: { url: "/pages/center/center" } },
      });
    }
  },
  /**
   * 计算两点之间距离
   * @param {Object} from 起始位置经纬度
   * @param {Array} to 终点位置经纬度
   * @param {Function} callback 回调函数
   */
  calculateDistance(from, to, callback) {
    qqmapsdk.calculateDistance({
      mode: "driving",
      from,
      to,
      success(res) {
        console.log("计算两点之间距离：", res);
        callback(res);
      },
      fail: function (error) {
        console.error(error);
      },
    });
  },
  /**
   * 打开socket
   */
  openSocket() {
    let _this = this;
    // 创建websocket对象
    this.websocket = new websocket({
      // true代表启用心跳检测和断线重连
      heartCheck: true,
      isReconnection: true,
    });
    // 建立连接
    this.linkWebsocket();
    // 监听websocket状态
    this.websocket.onSocketClosed({
      url: this.data.websocketUrl + wx.getStorageSync("customerId"),
      success(res) {
        // console.log(res)
      },
      fail(err) {
        console.log(err);
      },
    });
    // 监听网络变化
    this.websocket.onNetworkChange({
      url: this.data.websocketUrl + wx.getStorageSync("customerId"),
      success(res) {
        console.log(res);
      },
      fail(err) {
        console.log(err);
      },
    });
    // 监听服务器返回
    this.websocket.onReceivedMsg((result) => {
      console.log("app.js收到服务器内容：" + result.data);
      if (result.data == "ok") {
        // _this.hiddenStopParkDialog()
        wx.showToast({
          title: "请在15分钟内离场，超时将重新计费",
          duration: 5000,
          icon: "none",
        });
        clearInterval(countTime);
      }
      if (result.data == "buy-card-success") {
        wx.redirectTo({ url: "../grade/grade" });
      }
      //  进场
      if (result.data.indexOf("car-in-park") != -1) {
        setTimeout(function () {
          _this.getStopingCar();
        }, 1000);
      }
      //  出场通知
      if (result.data.indexOf("car-out-park") != -1) {
        setTimeout(function () {
          let markers = _this.data.markers;
          markers.forEach((element, index) => {
            delete markers[index].customCallout;
          });
          console.log("出场通知");
          _this.getStopingCar(); //  在场车辆
          _this.getReserve();
        }, 1000);
      }

      // 要进行的操作
    });
    // 监听websocket异常
    this.websocket.onSocketError({
      url: this.data.websocketUrl + wx.getStorageSync("customerId"),
      success(res) {
        console.log("index-监听websocket异常成功", res);
      },
      fail(err) {
        console.log("监听websocket异常失败", res);
      },
    });
  },
  linkWebsocket() {
    // 建立连接
    this.websocket.initWebSocket({
      url: this.data.websocketUrl + wx.getStorageSync("customerId"),
      success(res) {
        // that.countDown()
      },
      fail(err) {
        console.log(err);
      },
    });
  },
  // websocket超时处理
  countDown() {
    let count = 10;
    let that = this;
    countTime = setInterval(function () {
      count--;
      if (count <= 0) {
        clearInterval(countTime);
        that.websocket.closeWebSocket();
        // that.hiddenStopParkDialog()
        wx.showToast({
          title: "预出场失败，请重试",
          duration: 2000,
          icon: "none",
        });
      }
    }, 1000);
  },
  /**
   * 车主位置实时监听
   */
  locationChange() {
    wx.startLocationUpdate({
      success: (res) => {
        wx.onLocationChange((result) => {
          var markers = this.data.markers;
          for (var item of markers) {
            if (!item) {
              continue;
            }
            //  车主位置marker
            if (item.id == 0) {
              item.latitude = result.latitude;
              item.longitude = result.longitude;
            }
          }
          this.setData({ markers: markers });
        });
      },
      fail: (err) => {
        console.log(err, "车主实时位置获取失败");
      },
    });
  },
  /**
   * 关闭停车信息弹窗
   */
  // hiddenStopCarDialog() {
  //   this.setData({
  //     stopCarDialog: false
  //   })
  // },
  /**
   * 关闭停车信息弹窗
   */
  hiddenStopCarOutDialog() {
    this.setData({ stopCarOutDialog: false });
    this.getStopingCar(false);
  },
  closePopup() {
    this.setData({
      payBehalfDialog: false,
    });
  },
  /**
   * 显示离场车辆
   */
  // showStopCar() {
  //   let stopingCarList = this.data.stopingCarList
  //   if (stopingCarList.length > 1) {
  //     stopingCarList[0].checked = true
  //     this.setData({
  //       stopCarOutDialog: true,
  //       stopingCarList: stopingCarList
  //     })
  //   }
  //   this.getCurrOrder(0, true)
  // },
  /**
   * 图片预览
   */
  showImage(e) {
    let markerPark = this.data.markerPark;
    wx.previewImage({
      urls: markerPark.parkImgUrl.split(","),
      current: e.currentTarget.dataset.img,
    });
  },
  /**
   * 图片切换
   */
  parkImgChange(e) {
    this.setData({
      parkImgCurr: e.detail.current,
    });
  },
  /**
   * 获取新发放优惠券
   */
  getCouponTips() {
    let that = this;
    let url = "/customer/ticket/getTipsTicket";
    let parmas = {
      customerId: wx.getStorageSync("customerId"),
    };
    request.http(url, "POST", parmas).then((res) => {
      console.log(" 获得优惠券 ", res);
      let data = res.data;
      if (data.code == 200) {
        if (data.data.length > 0) {
          that.setData({
            couponTipList: data.data,
            couponTipsDialog: true,
          });
        }
      }
    });
  },
  /**
   * 取消优惠券提示
   */
  closeCouponTips() {
    // 改成取消弹窗
    this.setData({
      couponTipsDialog: false,
    });
  },
  /**
   * 跳转轮播图详情页面
   */
  toBannerDetail() {
    wx.navigateTo({
      url: "/pages/indexBannerDetail/indexBannerDetail",
    });
  },
  /**
   * 优惠券
   */
  toCoupon(e) {
    this.closeCouponTips();
    console.log(e);
    var selectedTicketIndex = 2;
    let query = selectedTicketIndex;
    wx.navigateTo({
      url: "../cust-ticket/custTicket?state=" + query,
      // url: e.currentTarget.dataset.path,
    });
  },
  /**
   * 跳转预约页面
   */
  toSubscribe() {
    wx.navigateTo({ url: "/pages/nearby/nearby?reserve=1" });
  },

  /**
   * 跳转办理月租页面
   */
  toHandleMonth() {
    if (this.data.token) {
      wx.navigateTo({ url: "../for-rent/forRent?monthCard=1" });
    } else {
      //  获取用户信息
      this.getUserProfile({
        currentTarget: { dataset: { url: "/pages/nearby/nearby?monthCard=1" } },
      });
    }
  },
  /**
   * 跳转领券停车页面
   */
  toHandleRecharge() {
    if (this.data.token) {
      // wx.navigateTo({ url: '/pages/vipCharge/vipCharge?index=0' })
      wx.navigateTo({ url: "/pages/getTicket/getTicket?parkTicket=1" });
    } else {
      //  获取用户信息
      this.getUserProfile({
        currentTarget: {
          dataset: { url: "/pages/vipCharge/vipCharge?index=0" },
        },
      });
    }
  },
  /**
   * 获取用户信息
   */
  getUserProfile(e) {
    wx.getUserProfile({
      desc: "用于完善会员资料",
      success: (res) => {
        console.log("获取用户信息：", res);
        this.setData({ userInfo: res.userInfo });
        wx.setStorageSync("userInfo", res.userInfo);
        wx.login({
          success: (res) => {
            this.getToken(
              res.code,
              e.currentTarget.dataset.url == null
                ? e.detail
                : e.currentTarget.dataset.url
            );
          },
        });
      },
    });
  },

  /**
   * 开启定位
   */
  openUserLocation() {
    let _this = this;
    wx.showModal({
      content: "请您先授权位置信息",
      confirmText: "去授权",
      showCancel: false,
      success(res) {
        if (res.confirm) {
          wx.openSetting({
            withSubscriptions: true,
            success(locationRes) {
              _this.setData({ isLocalLocation: true });
              wx.setStorageSync(
                "isLocalLocation",
                locationRes.authSetting["scope.userLocation"]
              );
            },
          });
        } else {
          console.log("get location fail");
        }
      },
    });
  },
  /**
   * 获取用户当前位置
   */
  getLocation() {
    return new Promise((resolve, reject) => {
      let _this = this;
      wx.getLocation({
        type: "gcj02",
        success(res) {
          console.log("获取用户当前位置成功", res);
          _this.setData({
            longitude: res.longitude,
            latitude: res.latitude,
            hasmarkers: true,
          });
          //  获取停车场
          _this.getParks(res.longitude, res.latitude);
          //  获取当前地理位置
          _this.getLocal(res.latitude, res.longitude);
          console.log(res.latitude, res.longitude);
          //  移动到用户当前位置
          _this.MapContext.moveToLocation({
            longitude: Number(res.longitude),
            latitude: Number(res.latitude),
          });

          resolve(res);
        },
        fail(err) {
          console.log("获取当前位置失败：", err);
          // 判断code+msg都满足才会提示定位失败，不然会有提示频繁调用定位，也会提示定位失败
          if (
            err.errCode === 2 &&
            err.errMsg == "getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF"
          ) {
            wx.showModal({
              content: "定位失败,请在系统设置中打开定位服务",
              confirmText: "我知道了",
              showCancel: false,
            });
          }
          // wx.showToast({ title: '获取当前位置失败', icon: 'none',duration: 1000 })
          //  如果未允许定位，则跳转定位设置页面
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting["scope.userLocation"]) {
                //  开启定位
                _this.openUserLocation();
              }
            },
          });
          reject(err);
        },
      });
    });
  },

  /**
   * 获取当前地理位置
   * @param {Number} latitude 维度
   * @param {Number} longitude 精度
   */
  getLocal: function (latitude, longitude) {
    let _this = this;
    qqmapsdk.reverseGeocoder({
      location: { latitude: latitude, longitude: longitude },
      success: function (res) {
        console.log("获取当前地理位置：", res.result);
        _this.setData({
          province: res.result.ad_info.province,
          city: res.result.ad_info.city,
        });
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   */
  getToken(code, src) {
    console.log(src);
    let userInfo = this.data.userInfo;
    console.log(userInfo);
    let params = {
      avatar: userInfo.avatarUrl,
      code: code,
      nickname: userInfo.nickName,
      sex:
        userInfo.gender == 0
          ? "UNKNOWN"
          : userInfo.gender == 1
          ? "MEN"
          : "WOMEN",
    };
    request.http("/customer/info/authorize", "POST", params).then((res) => {
      console.log("获取token：0000000000000000000000000", res);
      var data = res.data;
      if (data.code == 200) {
        wx.setStorageSync("token", data.data.token);
        wx.setStorageSync("customerId", data.data.customerId);
        this.setData({
          token: data.data.token,
          userInfo: wx.getStorageSync("userInfo"),
          //应该会出  地址重复问题
          // websocketUrl: app.globalData.websocketUrl + 'customer/' + data.data.customerId
        });
        this.getStopingCar(); //  在场车辆
        this.getReserve(); //  预约
        this.getCustomerLeftTime(); //  车主剩余服务
        this.openSocket(); //  打开socket
        this.getCouponTips(); //  卡券
        //  跳转页面
        if (typeof src == "string") {
          console.log("获取token后跳转页面：", src);
          wx.navigateTo({ url: src });
        }
        //判断是不是新用户，新用户授权后跳转 绑定车牌页面
        if (data.data.isNew == 1) {
          wx.navigateTo({ url: "../licencePlate/licencePlate" });
        }
      } else {
        wx.removeStorageSync("userInfo");
      }
    });
  },

  /**
   * 小程序更新
   */
  miniProgranUpdate() {
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log("请求完新版本信息的回调：", res);
    });
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: "更新提示",
        content: "新版本已经准备好，是否重启应用？",
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        },
      });
    });

    updateManager.onUpdateFailed(function () {
      console.log("新版本下载失败");
    });
  },
  /**
   * 获取marker
   */
  getMarker(id, longitude, latitude, iconPath, width, height) {
    return {
      id: id,
      longitude: longitude,
      latitude: latitude,
      iconPath: iconPath,
      width: width,
      height: height,
      zIndex: 1400,
    };
    // return { id: id, longitude: longitude, latitude: latitude, iconPath: iconPath, width: width, zIndex: 2000 }
  },
  /**
   * 获取marker的icon
   */
  getMarkerIcon(marker) {
    //  默认手动支付
    let prefix = "manual";
    //  无感支付
    if (marker.isAutopay == 1) {
      prefix = "automatic";
    }
    let imgUrl = "";

    if (marker.emptyParkSpace <= 0) {
      imgUrl =
        "https://mis.lmtc.zmzncs.com/file/WeChat/" + prefix + "-point0.png";
    }
    if (marker.emptyParkSpace >= 1 && marker.emptyParkSpace < 10) {
      imgUrl =
        "https://mis.lmtc.zmzncs.com/file/WeChat/" + prefix + "-point1+.png";
    }
    if (marker.emptyParkSpace >= 10) {
      imgUrl =
        "https://mis.lmtc.zmzncs.com/file/WeChat/" + prefix + "-point10+.png";
    }
    if (marker.emptyParkSpace >= 20) {
      imgUrl =
        "https://mis.lmtc.zmzncs.com/file/WeChat/" + prefix + "-point20+.png";
    }
    //  停车场可预约
    if (marker.reserveRuleStatus == 1) {
      if (marker.emptyParkSpace <= 0) {
        imgUrl =
          "https://mis.lmtc.zmzncs.com/file/WeChat/" +
          prefix +
          "-reserve-point0.png";
      }
      if (marker.emptyParkSpace >= 1 && marker.emptyParkSpace < 10) {
        imgUrl =
          "https://mis.lmtc.zmzncs.com/file/WeChat/" +
          prefix +
          "-reserve-point1+.png";
      }
      if (marker.emptyParkSpace >= 10) {
        imgUrl =
          "https://mis.lmtc.zmzncs.com/file/WeChat/" +
          prefix +
          "-reserve-point10+.png";
      }
      if (marker.emptyParkSpace >= 20) {
        imgUrl =
          "https://mis.lmtc.zmzncs.com/file/WeChat/" +
          prefix +
          "-reserve-point20+.png";
      }
    }
    //  停车场有停车券
    if (marker.hasParkTicket == 1) {
      if (marker.emptyParkSpace <= 0) {
        imgUrl =
          "https://mis.lmtc.zmzncs.com/file/WeChat/" +
          prefix +
          "-park-ticket-point0.png";
      }
      if (marker.emptyParkSpace >= 1 && marker.emptyParkSpace < 10) {
        imgUrl =
          "https://mis.lmtc.zmzncs.com/file/WeChat/" +
          prefix +
          "-park-ticket-point1+.png";
      }
      if (marker.emptyParkSpace >= 10) {
        imgUrl =
          "https://mis.lmtc.zmzncs.com/file/WeChat/" +
          prefix +
          "-park-ticket-point10+.png";
      }
      if (marker.emptyParkSpace >= 20) {
        imgUrl =
          "https://mis.lmtc.zmzncs.com/file/WeChat/" +
          prefix +
          "-park-ticket-point20+.png";
      }
    }
    return imgUrl;
  },

  //隐藏弹框，平台发放的停车券
  closeParkingShow() {
    this.setData({
      parkingShow: false,
    });
  },
  //首页提醒的停车券
  parkingList() {
    request
      .http("/customer/ticket/getTipsParkTicket", "GET", {})
      .then((res) => {
        console.log(res);
        let data = res.data;
        if (data.code == 200) {
          if (data.data.length != 0) {
            this.setData({
              parkingShow: true,
              parkingList: data.data,
            });
          } else {
            this.closeParkingShow();
          }
        }
      });
  },
  //跳转查看  停车劵。我的卡卷页面
  toParking() {
    this.closeParkingShow();
    wx.navigateTo({
      url: "/pages/cust-ticket/custTicket",
    });
  },

  async getParkingServices(plateNumber) {
    const { data: res } = await myRequest({
      url: "wxPay/searchCarStatus",
      data: { plateNumber },
    });
    console.log(res.retData.service_state);
    if (res.retData.service_state == "NORMAL") {
      console.log('已开通');
      this.setData({
        openNoninductive: false
      })
    }
  },

  // 微信支付分停车
  async openWxFreePay() {
    let _this = this;
    let plateNumber = this.data.orderInfo.carNumber;
    const { data: res } = await myRequest({
      url: "wxPay/searchCarStatus",
      data: { plateNumber },
    });
    console.log(res.retData.service_state);
    if (res.retData.service_state != "NORMAL") {
      // 跳转微信开通支付分服务页
      wx.navigateToMiniProgram({
        appId: "wxbcad394b3d99dac9",
        path: "/pages/auth-creditpay/auth-creditpay",
        extraData: {
          mchid: res.retData.mchid,
          sub_mchid: res.retData.sub_mchid,
          openid: res.retData.openid,
          plate_number: res.retData.plate_number,
          plate_color: res.retData.plate_color,
          trade_scene: res.retData.trade_scene,
        },
        success(resp) {
          console.log(resp);
          _this.setData({
            openNoninductive: false,
          });
        },
        fail(err) {
          console.log(err);
        },
      });
    }
  },
  // 免密支付该账单
  async goWxFreePay() {
    let _this = this;
    let orderInfo = this.data.orderInfo
    let orderId = orderInfo.orderCode;
    let plateNumber = orderInfo.carNumber;
    const { data: res } = await myRequest({
      url: "/wxPay/payParking",
      data: { plateNumber,orderId },
    });
    console.log(res.retData.data);
    let result = JSON.parse(res.retData.data)
    if(res.retData.code == "200") {
      console.log(result.trade_state);
      if(result.trade_state == "SUCCESS") {
        wx.showToast({
          title: '支付成功',
          duration:1500,
          success:res=>{
            console.log(res);
            _this.setData({
              orderState: false
            })
          }
        })
      }
    }
  },
});
